package cc.grapevine.vps;

import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import cc.grapevine.vps.http.HttpManager;
import cc.grapevine.vps.http.HttpRequestVps;
import cc.grapevine.vps.http.HttpResponseVps;
import cc.grapevine.vps.http.URLManager;
import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;

public class VpsService extends Service implements HttpManager.HttpListen
{

	private HttpManager m_HttpManager;

	private static final int TIME = 10 * 60 * 1000;

	private Timer m_Timer;

	private TimerTask m_Task;

	private HttpRequestVps m_RequestVpsList = new HttpRequestVps(Action.GET_VPS_LIST, URLManager.LIST_URL);

	private Map<String, VpsData> m_Data;

	private boolean m_timerStarted;

	@Override
	public void onCreate()
	{
		super.onCreate();
		init();
	}

	private void init()
	{
		m_HttpManager = HttpManager.getInstence();
		m_Data = UserManager.getIntence().getDataHashMap();
		m_timerStarted = false;
		m_HttpManager.setListen(this);
		m_HttpManager.start();
	}

	@Override
	public void onStart(Intent intent, int startId)
	{
		super.onStart(intent, startId);
		m_HttpManager.addRequest(m_RequestVpsList);
	}

	@Override
	public void onDestroy()
	{
		super.onDestroy();
		stopTimer();
		m_HttpManager.stop();
	}

	private void startTimer()
	{
		m_timerStarted = true;
		m_Timer = new Timer();
		m_Task = new TimerTask()
		{
			@Override
			public void run()
			{
				for (String key : m_Data.keySet())
				{
					VpsData data = m_Data.get(key);
					HttpRequestVps requestVps = new HttpRequestVps(Action.UPDATE_STATUS, URLManager.createDecStatus(
							data.getId(), data.getName()));
					
					requestVps.setId(data.getId());
					requestVps.setName(data.getName());
					
					if (null != m_HttpManager)
					{
						m_HttpManager.addRequest(requestVps);
					}
					else
					{
						break;
					}
				}
			}
		};
		m_Timer.schedule(m_Task, 500, TIME);
	}

	private void stopTimer()
	{
		m_timerStarted = false;
		if (null != m_Timer)
		{
			m_Timer.cancel();
			m_Timer = null;
		}
		if (null != m_Task)
		{
			m_Task.cancel();
			m_Task.cancel();
		}
	}

	@Override
	public void httpResponse(HttpResponseVps responseVps)
	{
		Intent intent = new Intent();
		Bundle bundle = new Bundle();
		bundle.putSerializable("data", responseVps);
		intent.putExtras(bundle);
		if (responseVps.httpError)
		{
			intent.setAction(Action.HTTP_ERROR);
		}
		else if ("-1".equals(responseVps.content))
		{
			intent.setAction(Action.NO_LOGIN);
		}
		else if ("-2".equals(responseVps.content))
		{
			intent.setAction(Action.COMMUNICATION_ERROR);
		}
		else
		{
			if (Action.GET_VPS_LIST.equals(responseVps.action))
			{
				try
				{
					JSONArray ja = new JSONArray(responseVps.content);
					for (int i = 0; i < ja.length(); i++)
					{
						JSONObject jb = (JSONObject) ja.get(i);
						String id = jb.getString("nodeid");
						String name = jb.getString("vmname");
						String key = id + name;

						VpsData data = m_Data.get(key);
						if (null == data)
						{
							data = new VpsData();
							data.setId(id);
							data.setName(name);
							m_Data.put(key, data);
						}
						else
						{
							data.setId(id);
							data.setName(name);
						}
					}

					if (!m_timerStarted)
					{
						startTimer();
					}
					intent.setAction(Action.GET_VPS_LIST);
				}
				catch (JSONException e)
				{
					e.printStackTrace();
					return;
				}

			}
			else if (Action.UPDATE_STATUS.equals(responseVps.action))
			{
				String key = responseVps.vpsData.getId() + responseVps.vpsData.getName();
				VpsData data = m_Data.get(key);
				if (null == data)
				{
					return;
				}
				data.setStatues(Statues.getStatues(Integer.parseInt(responseVps.content)));
				intent.setAction(Action.UPDATE_STATUS);
			}
			else
			{
				intent.setAction(responseVps.action);
			}
		}
		sendBroadcast(intent);
	}

	@Override
	public IBinder onBind(Intent intent)
	{
		return null;
	}
}